package com.ybkj.daijia.server.controller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.config.RentApi;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.model.notice.Notice;
import com.ybkj.daijia.server.model.notice.NoticeCategory;
import com.ybkj.daijia.server.model.notice.NoticeCategoryTop;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Blazk.
 */
@RestController
@RequestMapping(value = "rentnotice")
public class RentNoticeController {

    @Autowired
    private RentApi rentApi;

    @Autowired
    private SettingUtils settingUtils;

    @RequestMapping(value = "noticelist", method = RequestMethod.GET)
    public ModelAndView noticelist() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentnotice")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("rentnotice/notice");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "categorylist", method = RequestMethod.GET)
    public ModelAndView categorylist() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("rentnotice")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("rentnotice/category");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "insertNotice", method = RequestMethod.POST)
    public Map<String, Object> insertNotice(
        @RequestParam("title") String title,
        @RequestParam("seq") Integer seq,
        @RequestParam("categoryName") String categoryName,
        @RequestParam("notice") String notice,
        @RequestParam("category") Long category,
        @RequestParam("categoryTop") Long categoryTop,
        @RequestParam("categoryTopName") String categoryTopName,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();

        kv.add("seq", String.valueOf(seq));
        kv.add("title", title);
        kv.add("categoryName", categoryName);
        kv.add("categoryTopName", categoryTopName);
        kv.add("notice", notice);
        kv.add("category", String.valueOf(category));
        kv.add("categoryTop", String.valueOf(categoryTop));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.INSERT_NOTICE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "创建成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "deleteNotice", method = RequestMethod.POST)
    public Map<String, Object> deleteNotice(@RequestParam("id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.DELETE_NOTICE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "删除成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "updateNotice", method = RequestMethod.POST)
    public Map<String, Object> updateNotice(
        @RequestParam("id") Long id,
        @RequestParam(required = false, value = "title") String title,
        @RequestParam(required = false, value = "seq") Integer seq,
        @RequestParam(required = false, value = "categoryName") String categoryName,
        @RequestParam(required = false, value = "notice") String notice,
        @RequestParam(required = false, value = "category") Long category,
        @RequestParam(required = false, value = "categoryTop") Long categoryTop,
        @RequestParam(required = false, value = "categoryTopName") String categoryTopName,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        kv.add("seq", String.valueOf(seq));
        kv.add("title", title);
        kv.add("categoryName", categoryName);
        kv.add("categoryTopName", categoryTopName);
        kv.add("notice", notice);
        kv.add("category", String.valueOf(category));
        kv.add("categoryTop", String.valueOf(categoryTop));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.UPDATE_NOTICE, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "修改成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "selectNotice", method = RequestMethod.GET)
    public Notice selectNotice(@RequestParam("id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_NOTICE)
            .append("?appkey={appkey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().create();
                Notice notice = gson.fromJson(data.toString(), Notice.class);
                return notice;
            }
        }
        return null;
    }

    @RequestMapping(value = "selectNoticesByTitle", method = RequestMethod.GET)
    public Page<Notice> selectNoticesByTitle(
        @RequestParam(required = false, value = "category") Long category,
        @RequestParam(required = false, value = "categoryTop") Long categoryTop,
        @RequestParam(required = false, value = "title") String title,
        @RequestParam(required = false, value = "page") Integer page,
        @RequestParam(required = false, value = "rows") Integer rows,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL())
            .append(RentApi.SELECT_NOTICE_BY_TITLE)
            .append("?appkey={appkey}");
        if (StringUtils.isNotBlank(title)) {
            kv.put("title", title);
            builder.append("&title={title}");
        }
        if (category != null) {
            kv.put("category", String.valueOf(category));
            builder.append("&category={category}");
        }
        if (categoryTop != null) {
            kv.put("categoryTop", String.valueOf(categoryTop));
            builder.append("&categoryTop={categoryTop}");
        }
        page = Pager.getPage();
        rows = Pager.getLimit();
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        // {"code":0,"message":"成功","data":[{"id":1,"created":null,"categoryTop":1,"categoryTopName":"test1"}],"total":1}
        List<Notice> notices = new ArrayList<Notice>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray jsonArray = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                notices = gson.fromJson(jsonArray.toString(),
                    new TypeToken<List<Notice>>() {
                    }.getType());

            }
        }
        return new PageImpl<Notice>(notices, pageable, total);
    }

    @RequestMapping(value = "selectCategoryByPid", method = RequestMethod.GET)
    public List<NoticeCategory> selectCategoryByPid(
        @RequestParam("pid") Long pid, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL())
            .append(RentApi.SELECT_CATEGORY_BY_PID)
            .append("?appkey={appkey}");
        if (pid != null) {
            kv.put("pid", String.valueOf(pid));
            builder.append("&pid={pid}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().create();
                List<NoticeCategory> categorys = gson.fromJson(data.toString(),
                    new TypeToken<List<NoticeCategory>>() {
                    }.getType());
                return categorys;
            }
        }
        return null;
    }

    @RequestMapping(value = "insertCategory", method = RequestMethod.POST)
    public Map<String, Object> insertCategory(
        @RequestParam("categoryName") String categoryName,
        @RequestParam("seq") Integer seq,
        @RequestParam("pid") Long pid,
        @RequestParam("topType") Integer topType,
        @RequestParam(required = false, value = "topCategoryName") String topCategoryName,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("seq", String.valueOf(seq));
        kv.add("pid", String.valueOf(pid));
        kv.add("categoryName", categoryName);
        kv.add("topCategoryName", topCategoryName);
        kv.add("topType", String.valueOf(topType));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.INSERT_CATEGORY, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "创建成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "deleteCategory", method = RequestMethod.POST)
    public Map<String, Object> deleteCategory(@RequestParam("id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.DELETE_CATEGORY, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "删除成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "updateCategory", method = RequestMethod.POST)
    public Map<String, Object> updateCategory(
        @RequestParam("id") Long id,
        @RequestParam(required = false, value = "categoryName") String categoryName,
        @RequestParam(required = false, value = "seq") Integer seq,
        @RequestParam(required = false, value = "pid") Long pid,
        @RequestParam(required = false, value = "topCategoryName") String topCategoryName,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        kv.add("seq", String.valueOf(seq));
        kv.add("pid", String.valueOf(pid));
        kv.add("categoryName", categoryName);
        kv.add("topCategoryName", topCategoryName);
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.UPDATE_CATEGORY, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "修改成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "selectCategory", method = RequestMethod.GET)
    public NoticeCategory selectCategory(@RequestParam("id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL()).append(RentApi.SELECT_CATEGORY)
            .append("?appkey={appkey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().create();
                NoticeCategory category = gson.fromJson(data.toString(),
                    NoticeCategory.class);
                return category;
            }
        }
        return null;
    }

    @RequestMapping(value = "selectNoticeCategorysByCategoryName", method = RequestMethod.GET)
    public Page<NoticeCategory> selectNoticeCategorysByCategoryName(
        @RequestParam(required = false, value = "categoryName") String categoryName,
        @RequestParam(required = false, value = "rows") Integer rows,
        @RequestParam("pid") Long pid,
        @RequestParam(required = false, value = "page") Integer page,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL())
            .append(RentApi.SELECT_NOTICE_CATEGORY_BY_CATEGORY_NAME)
            .append("?appkey={appkey}");
        page = Pager.getPage();
        rows = Pager.getLimit();
        if (StringUtils.isNotBlank(categoryName)) {
            kv.put("categoryName", categoryName);
            builder.append("&categoryName={categoryName}");
        }
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (pid != null) {
            kv.put("pid", String.valueOf(pid));
            builder.append("&pid={pid}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<NoticeCategory> categorys = new ArrayList<NoticeCategory>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray jsonArray = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                categorys = gson.fromJson(jsonArray.toString(),
                    new TypeToken<List<Notice>>() {
                    }.getType());

            }
        }
        return new PageImpl<NoticeCategory>(categorys, pageable, total);
    }

    @RequestMapping(value = "insertCategoryTop", method = RequestMethod.POST)
    public Map<String, Object> insertCategoryTop(
        @RequestParam("categoryName") String categoryName,
        @RequestParam("topType") Integer topType,
        @RequestParam("seq") Integer seq, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");

        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("seq", String.valueOf(seq));
        kv.add("topType", String.valueOf(topType));
        kv.add("categoryName", categoryName);
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.INSERT_CATEGORY_TOP, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "创建成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "deleteCategoryTop", method = RequestMethod.POST)
    public Map<String, Object> deleteCategoryTop(@RequestParam("id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.DELETE_CATEGORY_TOP, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "删除成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "updateCategoryTop", method = RequestMethod.POST)
    public Map<String, Object> updateCategoryTop(
        @RequestParam("id") Long id,
        @RequestParam(required = false, value = "categoryName") String categoryName,
        @RequestParam("seq") Integer seq, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, Object> map = new HashMap<String, Object>();
        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("id", String.valueOf(id));
        kv.add("seq", String.valueOf(seq));
        kv.add("categoryName", categoryName);
        String result = rentApi.postMultiValueMap(rentApi.getApiBaseURL()
            + RentApi.UPDATE_CATEGORY_TOP, kv, settingUtils.get());
        JSONObject jo = new JSONObject(result);
        Integer code = jo.getInt("code");
        if (code == 0) {
            map.put("message", "修改成功");
            map.put("success", true);
        } else {
            map.put("message", jo.getString("message"));
            map.put("success", false);
        }
        return map;
    }

    @RequestMapping(value = "selectCategoryTop", method = RequestMethod.GET)
    public NoticeCategoryTop selectCategoryTop(@RequestParam("id") Long id,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL())
            .append(RentApi.SELECT_CATEGORY_TOP).append("?appkey={appkey}");
        Map<String, String> kv = new HashMap<String, String>();
        if (id != null) {
            kv.put("id", id + "");
            builder.append("&id={id}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());

        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                Gson gson = new GsonBuilder().create();
                NoticeCategoryTop categoryTop = gson.fromJson(data.toString(),
                    NoticeCategoryTop.class);
                return categoryTop;
            }
        }
        return null;
    }

    @RequestMapping(value = "selectNoticeCategoryTopsByCategoryName", method = RequestMethod.GET)
    public Page<NoticeCategoryTop> selectNoticeCategoryTopsByCategoryName(
        @RequestParam(required = false, value = "categoryName") String categoryName,
        @RequestParam(required = false, value = "rows") Integer rows,
        @RequestParam(required = false, value = "page") Integer page,
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL())
            .append(RentApi.SELECT_NOTICE_CATEGORY_TOP_BY_CATEGORY_NAME)
            .append("?appkey={appkey}");
        if (StringUtils.isNotBlank(categoryName)) {
            kv.put("categoryName", categoryName);
            builder.append("&categoryName={categoryName}");
        }

        page = Pager.getPage();
        rows = Pager.getLimit();
        if (rows != null) {
            kv.put("rows", String.valueOf(rows));
            builder.append("&rows={rows}");
        }
        if (page != null) {
            kv.put("page", String.valueOf(page + 1));
            builder.append("&page={page}");
        }
        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<NoticeCategoryTop> categoryTops = new ArrayList<NoticeCategoryTop>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");

            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray jsonArray = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().create();
                categoryTops = gson.fromJson(jsonArray.toString(),
                    new TypeToken<List<NoticeCategoryTop>>() {
                    }.getType());

            }
        }
        return new PageImpl<NoticeCategoryTop>(categoryTops, pageable, total);
    }

    @RequestMapping(value = "selectAllCategoryTop", method = RequestMethod.GET)
    public List<NoticeCategoryTop> selectAllCategoryTop(
        HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Map<String, String> kv = new HashMap<String, String>();
        StringBuilder builder = new StringBuilder();
        builder.append(rentApi.getApiBaseURL())
            .append(RentApi.SELECT_ALL_CATEGORY_TOP)
            .append("?appkey={appkey}");

        String result = rentApi.get(builder.toString(), kv, settingUtils.get());
        List<NoticeCategoryTop> categoryTops = new ArrayList<NoticeCategoryTop>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().create();
                List<NoticeCategoryTop> categorytops = gson.fromJson(
                    data.toString(),
                    new TypeToken<List<NoticeCategoryTop>>() {
                    }.getType());
                return categorytops;
            }
        }
        return categoryTops;
    }

}
